import { Component } from "react";
import Drag from "../../components/skin/Common/Drag"
import RequestOrthographic from '../../services/orthographic';
import Retrieve from '../../services/homeMap'
import {
    Layer,
    Map,
    Point,
    transformGCJ2WGS,
    Overlay
} from "../../modules/CloudMap/src/Cloud";
import {
    ModalIcon,

} from "../../modules/CloudMap/src/Components/Common";
import {
    message,
    notification
} from "antd";
import { Event } from "../../modules/CloudMap/src/Cloud"

import copy from 'copy-to-clipboard';
import {
    MImg,
    MSearch,
    MTool,
    MIcon,
    Popup,
    BatchPoint
} from '../../components/skin/map';

interface MapProps {

}
interface MapState {
    onlineCloudImgList: any[];
    imgRightIs_: boolean;
    MapObject: any[];
    currentPicture: number;
    MIconList: any[];
    listMode: any[];
    pointEditStatus: any[];
    cursorMapStyle: boolean;
    pointEditModleIs_: boolean;
    VectorSource: any;
    webGlVector: any;
    Icons: any;
    IconsSub: any;
    OverlayData: any;
    Overlays: any;
    currtZoom: number;
    contentType: number;
    twiceEditIs_: boolean;
    batchPupopIs_: boolean;
    layerStatus: any;
    PointDataList: any[];

}

const { mapData, orthographicData } = require("../data");
const scss = require('../../assets/styles/map.module.scss');

interface MapProps {

}





export default class MapSkin extends Component<MapProps, MapState> {
    maps: any;
    layer: any;
    timer: any;
    isSearch: any;
    Events: any;
    constructor(props: any) {
        super(props)
        this.state = {
            onlineCloudImgList: [],
            imgRightIs_: false,
            MapObject: [],
            currentPicture: 0,
            listMode: [],
            MIconList: [],
            pointEditStatus: [false, false, false, false, false],
            cursorMapStyle: true,
            pointEditModleIs_: false,
            VectorSource: null,
            webGlVector: null,
            Icons: null,
            IconsSub: {
                longitude: 0,
                latitude: 0,
                text: '',
                color: '#fff',
                url: `${process.env.PUBLIC_URL}images/icon/blue.svg`,
                name: '',
                content: "",
                id: 0,
                type: 1
            },
            OverlayData: {
                status: false
            },
            Overlays: null,
            currtZoom: 0,
            twiceEditIs_: false,
            batchPupopIs_: false,
            contentType: 1,
            layerStatus: {
                webgl: true,
                ordinary: false
            },
            PointDataList: []
        };


    }

    componentDidMount() {
        this.initImg();
        this.DH()
    }
    // 初始化地图参数
    initImg = () => {



        this.setState({
            onlineCloudImgList: mapData
        }, () => {
            // Initialize the cloud map
            this.layer = new Layer();
            // Create a layer object , Source configures map parameters
            let layers = this.layer.TileLayer({ Source: mapData[2] });
            let layers1 = this.layer.TileXYZ({ Source: orthographicData[0] });
            // let layers2 = this.layer.TileLayer({ Source: r[2] });
            // let layers3 = this.layer.TileCWMS({ Source: r[3] });
            // Creating a map object
            this.maps = new Map({
                id: 'map',
                layers: [...layers, ...layers1],
                zoom: 13,
                coordinates: [119.87719099027917, 28.438025413550477]
            });
            this.Events = new Event(this.maps);
            this.setState({
                MapObject: layers
            });
            this.onClickSetCoordinate();

            this.moveend();


            this.getPoint();


        });


    }
    /**
     * 鼠标移动获取当前层级
     */
    moveend = () => {

        this.Events.Moveend((currtZoom: any) => {
            this.ControlPoint(currtZoom)
            this.setState({
                currtZoom
            })
        })
    }


    /**
     * 控制点位
     */
    ControlPoint = (num: number) => {
        let { VectorSource, webGlVector, layerStatus, PointDataList } = this.state;
        if (num > 18 && !layerStatus.ordinary) {

            this.maps.addLayer(Point.concrltLayer(Point.zsPoint(PointDataList)))
            layerStatus.ordinary = true;
            layerStatus.webgl = false;

            webGlVector.getFeatures().forEach((it: any) => {
                it.removeSelf()
            });
            webGlVector = null;
            this.setState({
                layerStatus,
                webGlVector: Point.webGlVector
            });

        } else if (num <= 18 && !layerStatus.webgl) {
            this.maps.addLayer(Point.wenGlLayer(Point.webGlPoint(PointDataList)))
            layerStatus.ordinary = false;
            layerStatus.webgl = true;
            VectorSource.getFeatures().forEach((it: any) => {
                it.removeSelf()
            });
            VectorSource = null;
            this.setState({
                layerStatus,
                VectorSource: Point.VectorSource
            });

        }


    }
    /**
     * 点击获取坐标
     */
    onClickSetCoordinate = () => {
        this.Events.singleclick((e: any) => {
            if (this.maps.hasFeatureAtPixel(e.pixel)) {
                var feature = this.maps.getFeaturesAtPixel(e.pixel)
                this.popupOver(feature[0]);
                return;
            } else {

                var textArea = document.createElement('textarea');
                textArea.style.position = 'fixed';
                textArea.style.left = '-10000px';
                textArea.style.top = '-10000px';
                document.body.appendChild(textArea);
                var a: any = document.getElementById("demoInputw");

                textArea.value = a.innerText;
                textArea.select();

                document.execCommand('copy');
                document.body.removeChild(textArea);

                message.success("复制成功")
            }
        });
        this.Events.setdblclick((e: any) => {

            if (this.maps.hasFeatureAtPixel(e.pixel)) {
                var feature = this.maps.getFeaturesAtPixel(e.pixel)[0];
                this.twiceEdit(feature);
                return;
            }
        })
    }






    DH = () => {
        let { MIconList } = this.state;
        MIconList.push(<MIcon>er</MIcon>);
        this.setState({
            MIconList
        })
        // return <MIcon>er</MIcon>
    }
    setInputStatus = (sub: any) => {
        let status = [false, false, false, false, false];
        status[sub] = true;
        let IconsSub = { ...this.state.IconsSub }
        /**
         * 当类型选择监控时
         */
        IconsSub.type = Number(sub + 1);

        let contentType = sub + 1;
        if (sub === 3) {
            this.setMonitor();
            IconsSub.content = 0;
            this.setState({
                pointEditStatus: status,
                contentType,
                IconsSub
            });

            this.setIcon(`${process.env.PUBLIC_URL}images/icon/rotation_mat/90度.svg`)
        }
        this.setState({
            pointEditStatus: status,
            contentType,
            IconsSub
        });

    }
    /**
     * 如果是监控点位的话
     */
    setMonitor = () => {
        let { VectorSource, Icons, IconsSub } = this.state;

    }
    stePointStart = () => {
        this.setState({
            cursorMapStyle: false
        });
        this.getTips();
        Point.SinClick(this.maps, (f: any, p: any) => {

            this.setState({
                cursorMapStyle: true,
                pointEditModleIs_: true,
                Icons: p
            }, this.setPointDaultValue);
        });


    }
    setPointDaultValue = () => {
        let { Icons, IconsSub } = this.state;
        IconsSub.text = Icons.style_.text_.text_;
        IconsSub.longitude = Icons.geometryChangeKey_.target.flatCoordinates[0];
        IconsSub.latitude = Icons.geometryChangeKey_.target.flatCoordinates[1];

        this.setState({
            IconsSub
        })
    }
    /**
     * 左下角提示信息框
     */
    getTips = () => {
        notification.info({
            message: `二维地图标点`,
            description:
                '双击视觉范围内任意一点，将完成标点',
            placement: 'bottomLeft'
        });
    }
    /**
     * 实时更新图标的动态属性
     */
    setPointStyle = () => {
        let { VectorSource, Icons, IconsSub } = this.state;

        // 移除
        VectorSource.removeFeature(Icons);
        Icons.setStyle(Point.setStyle(IconsSub));
        Icons.setGeometry(Point.setGeometry(IconsSub));
        Icons.set("data", { ...IconsSub.data, ...IconsSub });
        // 添加
        VectorSource.addFeature(Icons);
    }
    /**
     * 
     * @returns 
     * 更改点位的颜色
     */
    setColor = (e: any) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        sub.color = e;
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的Name
     * @returns 
     */
    setName = (e: any) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        sub.text = e;
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的图标
     * @returns 
     */
    setIcon = (e: any) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        sub.url = e;
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的坐标
     * @returns 
     */
    setGeometry = (e: any, type: string) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        if (type === "longitude") {
            sub.longitude = e;
        } else if (type === "latitude") {
            sub.latitude = e;
        }
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的展示信息
    //  * TODO {}
     * @returns 
     */
    setPoint = (e: any, type: string) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        if (type === "text") {
            sub.content = e;
        } else if (type === "latitude") {
            // sub.latitude = e;
        } else if (type === "monitor") {
            sub.content = e;
        }
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
    * 删除点位
   //  * TODO {}
    * @returns
    */
    deletePoint = () => {
        let { VectorSource, Icons, twiceEditIs_ } = this.state;

        let bioelement = () => {
            // 移除
            Icons.removeSelf()
            this.setState({
                pointEditModleIs_: !this.state.pointEditModleIs_,
                pointEditStatus: [false, false, false, false, false],
                Icons: null
            });
            message.success('删除成功');
        }
        if (twiceEditIs_) {
            RequestOrthographic.deletePoint(
                Icons.get("data").id,
                res => (res.code === 200) && bioelement()
            )
        } else bioelement()


    }
    /**
    * 保存成功点位
    * TODO {}
    * @returns
    */
    savePoint = () => {
        let { IconsSub, Icons, twiceEditIs_, contentType } = this.state;
        this.setState({
            pointEditModleIs_: !this.state.pointEditModleIs_,
            pointEditStatus: [false, false, false, false, false]
        });
        let sub = Icons.get("data");
        console.log(IconsSub.url);

        let data: any = {
            content: IconsSub.content,
            contentType: IconsSub.type,
            iconStyle: IconsSub.url,
            latitude: IconsSub.latitude,
            longitude: IconsSub.longitude,
            name: IconsSub.text,
            textColor: IconsSub.color
        };
        /**
         * 二次编辑添加id 
         */
        if (twiceEditIs_) {
            data.id = sub.id
        }
        RequestOrthographic.SavePoint(
            {
                ...data
            },
            res => {
                if (res.code === 200) {
                    sub.id = res.data
                    this.setState({
                        IconsSub: sub
                    }, this.setPointStyle)
                    message.success(twiceEditIs_ ? '修改成功' : '保存成功');
                    this.setState({
                        IconsSub: {
                            longitude: 0,
                            latitude: 0,
                            text: '',
                            color: '#fff',
                            url: `${process.env.PUBLIC_URL}images/icon/blue.svg`,
                            name: '',
                            id: 0,
                            content: "",
                            type: 1
                        },
                    })
                }
            }
        )

        // let eslect = this.maps.addInteractions('select');

        // eslect.on('select', (e: any) => {
        //     e.target.getFeatures().clear();
        //     console.log(e);
        //     Overlays && Overlays.setPosition(undefined);
        //     let ll = e.selected[0].getGeometry().flatCoordinates;
        //     Overlays = Overlay.addCOverlay({
        //         id: 'POPUP',
        //         coordinates: [parseFloat(ll[0]).toFixed(5), parseFloat(ll[1]).toFixed(5)]
        //     })
        //     this.maps.addOverlay(Overlays);
        //     this.setState({
        //         OverlayData: {
        //             status: true,
        //             ...e.selected[0].get('data')
        //         },
        //         Overlays: Overlays
        //     })

        // });
    }
    // 搜索点位跳转
    getPointTo = (Source: any) => {
        const { listMode } = this.state;
        if (listMode[Source].location && typeof (listMode[Source].location) === 'string') {
            let lonlat = listMode[Source].location.split(',');
            // 高德坐标转换
            let coordinates = transformGCJ2WGS({
                lon: parseFloat(lonlat[0]),
                lat: parseFloat(lonlat[1]),
                parameter: [1.9, 3]
            });
            listMode[Source].longitude = coordinates[0];
            listMode[Source].latitude = coordinates[1];
            let Icons = Point.Icons({ Source: [listMode[Source]] });
            this.maps.addLayer(Icons);
            this.maps.getView().animate({
                center: [listMode[Source].longitude, listMode[Source].latitude],
                duration: 1000,
                zoom: 18
            });
        }

    }
    /**
     * 获取点位信息、
     * 然后动态渲染
     * 在不同层级下用不同的方式去渲染，
     * 因为webGl渲染效率很高、但是不能高度自定义
     */
    getPoint = () => {
        this.setState({
            VectorSource: Point.VectorSource,
            webGlVector: Point.webGlVector,
        })
        RequestOrthographic.queryAll(res => {
            if (res.code === 200) {


                let webgk = Point.webGlPoint(res.data);

                let layer = Point.wenGlLayer(webgk);
                webgk.removeLyer = () => this.maps.removeLayer(layer);
                this.maps.addLayer(layer)
                this.setState({
                    PointDataList: res.data,
                    webGlVector: webgk
                })
            }

        })
    }



    /**
     * 
     * @param e 
     */
    popupOver = (feature: any) => {
        let { Overlays } = this.state;
        Overlays && Overlays.setPosition(undefined);

        let ll = feature.getGeometry().flatCoordinates;
        Overlays = Overlay.addCOverlay({
            id: 'POPUP',
            coordinates: [parseFloat(ll[0]).toFixed(5), parseFloat(ll[1]).toFixed(5)]
        })
        this.maps.addOverlay(Overlays);
        this.setState({
            OverlayData: {
                status: true,

                content: feature.get('data').content
            },
            Overlays: Overlays
        })

    }
    /**
     * 对已存入的点位进行二次编辑
     */
    twiceEdit = (e: any) => {
        let pointEditStatus = [false, false, false, false, false];
        pointEditStatus[e.get("data").type - 1] = true;

        this.setState({
            Icons: e,
            IconsSub: {
                ...e.get("data"),
                url: e.get("data").type === 4 ?
                    `images/icon/rotation_mat/90度.svg` :
                    e.get("data").iconStyle,
                type: e.get("data").type
            },
            pointEditModleIs_: true,
            twiceEditIs_: true,
            pointEditStatus
        })
    }
    /**
     * 
     * @returns 清除点位气泡
     * 
     */
    clearOverlay = () => {
        let { Overlays } = this.state;
        Overlays.setPosition(undefined);
        this.setState({
            Overlays: null
        })
    }
    /**
     * 鼠标在地图上移动事件
     * 当鼠标移动的时候获取当前鼠标所在位置的经纬度
     */
    onMouseMove = (sub: any) => {

        this.Events.MousePosition(sub, "demoInputw")
    }
    /**
     * 更新上传界面的弹框
     */
    setBatchIs = () => {
        this.setState({
            batchPupopIs_: !this.state.batchPupopIs_
        })
    }
    // 地名搜索
    getSearchDetails = (value: any) => {
        this.debounce(value === null ? '' : value);
    }
    // 防抖搜索
    debounce = (value: any) => {
        let that = this;
        clearTimeout(this.timer);
        this.timer = setTimeout(function () {
            // 切换为搜索
            if (!that.isSearch) {
                that.isSearch = true;
                Retrieve.PlaceNameSearch(value, (res) => {
                    if (res.data.tips) {
                        that.setState({
                            listMode: res.data.tips
                        })
                    }
                    that.isSearch = false;
                })
            }
        }, 200);
    }

    /**
     * 批量大导入点位信息
     * 用于批量导入监控点位信息
     * 通过弹窗导入点位至服务器
     * 由服务器解析完成之后返回数据信息
     * 在屏幕中渲染出来
     * 
     */
    onBatchPoint = (file: any) => {
        let files = new FormData();
        files.append("file", file);
        RequestOrthographic.batchPoint(
            files,
            (res) => {
                if (res.code === 200) {

                    this.setViewPoint();
                    message.success("上传成功")
                }
            }
        )
    }
    /**
     * 更新视图中所有的点位
     */
    setViewPoint = () => {
        let { VectorSource } = this.state;
        VectorSource.getFeatures().forEach((fl: any) => {
            VectorSource.removeFeature(fl)
        });
        this.getPoint()

    }
    // 更新地图
    updateMap = (su: number) => {
        let { onlineCloudImgList, MapObject } = this.state;
        // remove map
        MapObject.forEach(r => {
            this.maps.removeLayer(r);
        });
        let layer = this.layer.TileLayer({ Source: onlineCloudImgList[su] });
        // add map
        layer.forEach((element: any) => {
            this.maps.addLayer(element);
        });
        // update map
        this.setState({
            MapObject: layer,
            currentPicture: su
        });
    }
    render() {
        const {
            onlineCloudImgList,
            imgRightIs_,
            listMode,
            batchPupopIs_,
            pointEditStatus,
            cursorMapStyle,
            pointEditModleIs_,
            IconsSub,
            OverlayData,
            currtZoom,
            currentPicture
        } = this.state;
        return (
            <div className={scss['ol-admin']}>
                <div
                    id={'map'}
                    className={scss['map']}
                    style={{ cursor: cursorMapStyle ? 'crosshair' : 'default' }}
                    onMouseMove={this.onMouseMove}
                ></div>
                {
                    pointEditModleIs_ &&
                    <Drag
                        style={{
                            width: '18vw',
                            height: '45px',
                            position: 'absolute'
                        }}
                    >
                        <ModalIcon

                            defaultValue={IconsSub}
                            setName={this.setName}
                            setIcon={this.setIcon}
                            setColor={this.setColor}
                            setPoint={this.setPoint}
                            savePoint={this.savePoint}
                            deletePoint={this.deletePoint}
                            setGeometry={this.setGeometry}
                            pointEditStatus={pointEditStatus}
                            setInputStatus={this.setInputStatus}
                        />
                    </Drag>

                }


                <MTool
                    listMode={
                        <>
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/point.svg').default}
                                urls={require('../../modules/CloudMap/src/assets/icon/point.svg').default}
                                onClick={this.stePointStart}
                                status={true}
                            />
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/line.svg').default}
                                urls={require('../../modules/CloudMap/src/assets/icon/line.svg').default}
                                status={true}
                            />
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/pentagon.svg').default}
                                // onClick={this.stePointStart}
                                urls={require('../../modules/CloudMap/src/assets/icon/line.svg').default}
                                status={true}
                            />
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/circular.svg').default}
                                // onClick={this.stePointStart}
                                urls={require('../../modules/CloudMap/src/assets/icon/line.svg').default}
                                status={true}
                            />
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/REC.svg').default}
                                // onClick={this.stePointStart}
                                urls={require('../../modules/CloudMap/src/assets/icon/line.svg').default}
                                status={true}
                            />
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/scale.svg').default}
                                // onClick={this.stePointStart}
                                urls={require('../../modules/CloudMap/src/assets/icon/line.svg').default}
                                status={true}
                            />
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/area.svg').default}
                                // onClick={this.stePointStart}
                                urls={require('../../modules/CloudMap/src/assets/icon/line.svg').default}
                                status={true}
                            />
                        </>
                    }
                ></MTool>
                <MTool
                    listMode={
                        <>
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/bettol.svg').default}
                                urls={require('../../modules/CloudMap/src/assets/icon/updownicons.svg').default}
                                onClick={this.setBatchIs}
                                status={!batchPupopIs_}

                            />
                        </>
                    }
                    className={
                        {
                            marginTop: '16rem'
                        }
                    }
                ></MTool>
                <Popup
                    OverlayData={OverlayData}
                    clearOverlay={this.clearOverlay}
                />
                <div className={scss['ol-postiton']}>
                    <span className={scss['c-level']}>当前层级：{currtZoom}&#160;</span>
                    <span id="demoInputw" ></span>

                </div>
                {batchPupopIs_ &&
                    <BatchPoint
                        batchPointUpload={this.onBatchPoint}
                        setBatchIs={this.setBatchIs}
                    />
                }
                <MSearch
                    onSearch={(value) => this.getSearchDetails(value)}
                    listMode={listMode}
                    onChange={(value) => this.getSearchDetails(value.target.value)}
                    getPoint={this.getPointTo}
                />
                <MImg
                    imgList={onlineCloudImgList}
                    imgRightIs_={imgRightIs_}
                    currentPicture={currentPicture}
                    mouseGoOn={() => {
                        this.setState({
                            imgRightIs_: !imgRightIs_
                        });
                    }}
                    mouseGoOut={() => {
                        this.setState({
                            imgRightIs_: !imgRightIs_
                        });
                    }}
                    OnClick={(su) => this.updateMap(su)}
                />
            </div >
        )
    }
}



